<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="formShow">
          <template #year>
            <el-date-picker v-model="form.value3" type="year" placeholder="年份" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <el-button @click="importHandleClick">
          <span class="flex items-center"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </span>
        </el-button>
        <!-- <el-button icon="Upload" type="primary" @click="importHandleClick">导出</el-button> -->
        <div class="ml-auto"></div>
        <FieldSelectBtn :fieldSelectConfig="fieldSelectConfig" @submit="query" />
      </template>
    </VTable>
    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>

<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import { onMounted, ref, toRefs } from "vue"

const tableRef = ref()
import FieldSelectBtn from "@/views/salesInventory/components/FieldSelectBtn.vue"

import { longTermInventoryList } from "@/api/salesInventory"

// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const importHandleClick = async (e) => {
  let condition = {}
  DerivedCenterRef.value.open({
    tag_name: "LONG_TERM_INVENTORY",
    condition,
  })
}

// // 查询
const query = () => {
  tableRef?.value.query()
}
import { getAloneEnum } from "@/utils/enumUtils"
import { getWarehouseOptions } from "@/api/public"
import { apiGetWarehouseEnum } from "@/api"
const formShow = ref(false)
//获取下拉数据
onMounted(async () => {
  let oneKeys = ["wmsAttribute", "warehouse"]
  let optData = await getAloneEnum(oneKeys)
  oneKeys.forEach((key) => {
    originOption.value[key] = optData?.[key]
  })

  setTimeout(() => {
    formShow.value = true
  }, 100)
})

// 枚举 数据
const originOption = ref({})
const formOption = ref({ inline: true })
const publicStyle = { style: { width: "200px" } }
const fieldList = ref([
  {
    field: "sku",
    placeholder: "SKU",
    type: "textarea",
    ...publicStyle,
  },

  {
    field: "owner_id",
    type: "cascader",
    placeholder: "货主",
    multiple: true,
    collapseTags: true,
    ...publicStyle,
  },

  {
    field: "warehouse_id",
    type: "select",
    originField: "warehouse",
    multiple: true,
    collapseTags: true,
    options: {
      placeholder: "仓库",
    },
    ...publicStyle,
  },
  {
    field: "warehouse_attr",
    type: "select",
    originField: "wmsAttribute",
    multiple: true,
    collapseTags: true,
    options: {
      placeholder: "仓库属性",
    },
    ...publicStyle,
  },
  // 品类
  {
    field: "category",
    type: "cascaderNew",
    cascaderType: "category",
    placeholder: "产品品类",
    ...publicStyle,
  },
  {
    // label: "更新时间",
    field: "end_at",
    type: "dateTimeRangeNorm",
    itemProps: {
      type: "daterange",
      valueFormat: "YYYY-MM-DD",
    },
    style: { width: "300px" },
  },
  {
    field: "spu",
    placeholder: "SPU",
    type: "textarea",
    ...publicStyle,
  },
  {
    field: "ageRange",
    type: "numberRange",
    ...publicStyle,
    select: [
      { label: "库龄", value: "inventory_age" },
      { label: "延续库龄", value: "extend_inventory_age" },
    ],
  },
])
// 初始化时间
import { parseTime } from "@/utils/ruoyi"
const initDate = () => {
  const temp = new Date()
  temp.setTime(temp.getTime() - 3600 * 1000 * 24 * 560)
  return [new Date(temp.setHours(0, 0, 0, 0)), new Date(new Date().setHours(23, 59, 59, 0))].map((d) => parseTime(d, "{y}-{m}-{d}"))
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      ageRange: { type: "inventory_age", value: "" },
      end_at: initDate(),
    },
  },

  // rowConfig: { height: "150" },
  // tooltipConfig: {
  //   showAll: true,
  // },
  columns: [
    { type: "seq", field: "seq", title: "序号", width: 60 },
    {
      field: "sku",
      title: "自定义/SKU",
      width: 160,
      slots: {
        default: ({ row }) => (
          <div>
            <VText value={row.custom_sku} line={1} />
            <VText value={row.sku} line={1} />
          </div>
        ),
      },
    },
    {
      field: "FNsku",
      title: "FNsku/海外仓SKU",
      width: 140,
      slots: {
        default: ({ row }) => (
          <div>
            <VText value={row.fn_sku} line={1} />
            <VText value={row.fn_sku} line={1} />
          </div>
        ),
      },
    },
    { field: "owner_name", title: "货主", width: 140 },
    { field: "sku_cn_title", title: "产品名称", width: 200, line: 2 },
    { field: "spu", title: "SPU", width: 120 },
    { field: "category_text", title: "产品品类", width: 160, line: 2 },
    { field: "warehouse_name", title: "仓库", width: 100 },
    { field: "XXXXXXX", title: "在途库存", width: 100 },
    { field: "current_quantity", title: "当前库存", width: 100 },
    { field: "available_quantity", title: "可用库存", width: 100 },
    { field: "locked_quantity", title: "锁库", width: 100 },
    { field: "inventory_age", title: "库龄", width: 100 },
    { field: "extend_inventory_age", title: "延续库龄", width: 100 },
    { field: "weighted_cost", title: "加权金额", width: 100 },
    { field: "total_amount", title: "总金额", width: 100 },
  ],

  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        console.log("query")
        console.log(form)
        let params = {
          page: page.pageNum,
          page_size: page.pageSize,
          ...initForm(form),
        }

        return queryList(params)
      },
    },
  },

  showFooter: true,
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (column.title === "仓库") {
          return "合计"
        }
        if (countKey.includes(column.field)) {
          return sumNum(data, column.field)
        }
        return ""
      }),
    ]
  },
})
// 需要计算字段
const countKey = ["XXXXXXX", "current_quantity", "available_quantity", "locked_quantity", "inventory_age", "extend_inventory_age", "weighted_cost", "total_amount"]
const sumNum = (list, field) => {
  let count = 0
  list.forEach((item) => {
    count += Number(item[field] || 0)
  })
  return count
}

import { filterColumns } from "@/views/salesInventory/components/method.js"

const totalKey = ref("")
const queryList = async (params) => {
  // 表格列渲染配置
  let columnsData = [...tableOptins.columns]
  const { columns, key } = filterColumns(columnsData, fieldSelectConfig.value.columnsShow)
  totalKey.value = key
  tableRef?.value?.$table.loadColumn(columns)

  return await longTermInventoryList(params)
}
const fieldSelectConfig = ref({
  save: "longInventoryCollect",
  columnsShow: [],
  columns: [...tableOptins.columns],
})
// 组装查询条件
const initForm = (form) => {
  let { ageRange } = tableRef.value.getForm()
  form[ageRange.type] = {
    start: ageRange.value.min,
    end: ageRange.value.max,
  }
  if (form.end_at) {
    form.end_at = {
      start: form.end_at[0] || "",
      end: form.end_at[1] || "",
    }
  }

  let keys = ["sku", "spu"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v.trim())
  })
  return form
}
</script>
<style lang="scss" scoped>
:deep(.vxe-footer--row) {
  // background: #eff3fe;
  background: var(--base-table-hover-bg-color);
}
</style>
